import { reqGetUserInfo, reqUserLogin, reqUserLogout, reqUserRegister,reqUserAddressList } from '@/api'
import {getUserTempId} from '@/utils/userabout'
const state = {
  // 第一步：临时标识每次项目刷新都会获取一次，存储在state
  userTempId:getUserTempId(),
  // token:"", //我们如果不考虑自动登录，那么就直接初始化为字符串，但是如果要自动登录，那么需要从localStorage当中去获取
  token:localStorage.getItem('TOKEN_KEY'),//localStorage和sessionStorage获取到就获取到，获取不到返回null
  userInfo:{},
  userAddressList:[]
}
const mutations = {
  
  RECEIVE_TOKEN(state,token){
    state.token = token
  },

  RECEIVE_USERINFO(state,userInfo){
    state.userInfo = userInfo
  },

  RESET_TOKEN(state){
    state.token = ''
  },

  RESET_USERINFO(state){
    state.userInfo = {}
  },

  RECEIVE_USERADDRESSLIST(state,userAddressList){
    state.userAddressList = userAddressList
  }
}
const actions = {
  
  //注册用户
  async userRegister({commit},userInfo){
    const result = await reqUserRegister(userInfo)
    if(result.code === 200){
      return 'ok'
    }else{
      return Promise.reject(new Error('failed'))
    }
  },


  //登录用户
  async userLogin({commit},userInfo){
    const result = await reqUserLogin(userInfo)
    if(result.code === 200){
      commit('RECEIVE_TOKEN',result.data.token) //只是第一次登录的时候，需要给state当中存储token
      //如果需要自动登录，那么得把登录的token存储到localStorage
      localStorage.setItem('TOKEN_KEY',result.data.token)
      return 'ok'
    }else{
      return Promise.reject(new Error('failed'))
    }
  },

  //根据token获取用户信息
  async getUserInfo({commit}){
    const result = await reqGetUserInfo()
    if(result.code === 200){
      commit('RECEIVE_USERINFO',result.data)
      return 'ok'
    }else{
      return Promise.reject(new Error('failed'))
    }
  },
  
  //获取用户信息失败后需要清空token
  resetToken({commit}){
    commit('RESET_TOKEN')
    localStorage.removeItem('TOKEN_KEY')
  },

  //退出登录
  async userLogout({commit,dispatch}){
    const result = await reqUserLogout()
    if(result.code === 200){
      //退出成功需要清空用户的信息及token
      commit('RESET_USERINFO') //清空用户信息
      dispatch('resetToken') //清空用户token
      return 'ok'
    }else{
      return Promise.reject(new Error('failed'))
    }
  },

  //获取用户地址
  async getUserAddressList({commit}){
    const result = await reqUserAddressList()
    if(result.code === 200){
      commit('RECEIVE_USERADDRESSLIST',result.data)
    }
  }
}
const getters = {}
export default {
  state,
  mutations,
  actions,
  getters
}
